package com.beerandjesus.photogallery;

import com.beerandjesus.common.io.ImageFilenameFilter;
import com.beerandjesus.photogallery.image.PhotoGalleryImage;
import com.beerandjesus.photogallery.thumbnail.CreateThumbnail;

import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

public class PhotoGalleryPageOld {
    // Server docroot
    private String docRoot = null;
    // Number of pictures per page
    private int perPage = 10;
    // The page being looked at
    private int pageNum = 1;
    // List containing the images in the photo gallery
    private List images = null;
    // The index of the next image to display
    private int currentIndex = -1;
    // The starting index
    private int startIndex = -1;
    // Nav links
    private String navLinks = null;
    // Request parameter map
    private Map parameterMap = null;
    // The request URI
    private String requestUri = null;

    // The dirPath to the gallery directory
    private File dirPath = null;

    /**
     * Get a new PhotoGallery with a given doc root and
     * request URI, and parameter map
     */
    public PhotoGalleryPageOld(String docRoot, String requestUri, Map parameterMap) {
        this.docRoot = docRoot;
        this.parameterMap = parameterMap;
        this.requestUri = requestUri;
        // Figure out the page number
        this.pageNum = getPageNum();
    }

    /**
     * Initialize with basic parameters
     */
    public void init() {
        init(perPage);
    }

    /**
     * Initialize with a specific perPage setting
     */
    public void init(int perPage) {
        this.perPage = perPage;

        // Initialize indexes
        this.currentIndex = perPage * pageNum - perPage - 1;
        this.startIndex = currentIndex;

        // Get the dirPath to this directory
        dirPath = new File(docRoot + requestUri);
        if (!dirPath.isDirectory()) {
            dirPath = dirPath.getParentFile();
        }

        FilenameFilter iff = new ImageFilenameFilter();
        File[] files = dirPath.listFiles(iff);
        Collection c = photoGalleryImages(files);
        images = new ArrayList(c);
    }

    private Collection photoGalleryImages(File[] files) {
        Map pgImages = new HashMap();
        String fname = "";
        File f;
        for (int i = 0; i < files.length; i++) {
            f = (File) files[i];
            fname = f.getName();
            String fnameRoot = imageFilenameRoot(fname);
            PhotoGalleryImage image = null;
            if (pgImages.containsKey(fnameRoot)) {
                image = (PhotoGalleryImage) pgImages.get(fnameRoot);
            } else {
                image = new PhotoGalleryImage();
                pgImages.put(fnameRoot, image);
            }
            addToPhotoGalleryImage(image, f);
        }
        return pgImages.values();
    }

    private void addToPhotoGalleryImage(PhotoGalleryImage image, File file) {
        String filename = file.getName();
        if (isThumbnail(filename)) {
            image.setThumbUri(filename);
        } else if (isPicture(filename)) {
            image.setPictureUri(filename);
        }
    }

    private boolean isThumbnail(String filename) {
        StringTokenizer tokenizer = new StringTokenizer(filename, CreateThumbnail.THUMBNAIL_TOKEN_DELIMETER);
        return (tokenizer.countTokens() > 1);
    }

    private boolean isPicture(String filename) {
        StringTokenizer tokenizer = new StringTokenizer(filename, CreateThumbnail.THUMBNAIL_TOKEN_DELIMETER);
        return (tokenizer.countTokens() == 1);
    }

    private String imageFilenameRoot(String name) {
        StringTokenizer tokenizer = new StringTokenizer(name, ".", false);
        String fullRoot = tokenizer.nextToken();
        tokenizer = new StringTokenizer(fullRoot, "_tn", false);
        String imageRoot = tokenizer.nextToken();
        return imageRoot;
    }

    private int getPageNum() {
        String page_num = "1";
        int page;
        if (getParameter("pageNum") != null &&
                getParameter("pageNum").length() > 0) {
            page_num = getParameter("pageNum");
        }
        try {
            page = Integer.parseInt(page_num);
        } catch (NumberFormatException e) {
            page = 1;
        }
        if (page <= 0) {
            page = 1;
        }
        return page;
    }

    /**
     * Get a faceValue from the parameter map
     */
    private String getParameter(String key) {
        return (String) parameterMap.get(key);
    }

    /**
     * Get navigation links for this PhotoGallery
     */
    public String getNavLinks() {
        if (navLinks != null) {
            return (navLinks);
        }
        StringBuffer sb = new StringBuffer();
        int tpage = 1;
        int first = 1;
        for (int i = 1; i <= images.size(); i++) {
            boolean printIt = false;
            String open = "";
            String close = "";
            if (perPage * tpage == i) {
                first = i - perPage + 1;
                printIt = true;
            } else if (i == images.size()) {
                first = ((tpage - 1) * perPage) + 1;
                printIt = true;
            }
            if (printIt) {
                if (tpage != pageNum) {
                    open = "<a href=\"" + requestUri + "?pageNum="
                            + tpage + "\">";
                    close = "</a>";
                }
                sb.append(open + first + "-" + i + close + "\n");
                tpage++;
            }
        }
        navLinks = sb.toString();
        return (navLinks);
    }

    /**
     * Returns true if there is another image to display
     * for this page, false if not
     */
    public boolean hasNext() {
        if (currentIndex + 1 > startIndex + perPage) {
            return false;
        } else if (currentIndex + 1 >= images.size()) {
            return false;
        }
        return true;
    }

    /**
     * Get the next PhotoGalleryImage to display on this page
     */
    public PhotoGalleryImage getNext() {
        currentIndex++;
        return ((PhotoGalleryImage) images.get(currentIndex));
    }


    public int getCurrentIndex() {
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public File getDirPath() {
        return dirPath;
    }

    public void setDirPath(File dirPath) {
        this.dirPath = dirPath;
    }
}
